package com.neusoft.hifly.mybatis.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;

import com.neusoft.hifly.core.utils.GlobalConstants;
import com.neusoft.hifly.mybatis.handler.MyTableNameHandler;
import com.neusoft.hifly.mybatis.parsers.MyDynamicTableNameParser;

/**
 * Title: 核心类库
 * <p>
 * Description: MybatisPlus配置
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@EnableTransactionManagement // 开启事务管理
@Configuration
public class MybatisPlusConfig {
	@Value("${spring.datasource.druid.dbtype:mysql}")
	private String dbType;

	@SuppressWarnings("deprecation")
	@Bean
	public PaginationInterceptor paginationInterceptor() {
		// 设置方言类型
		final PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
		paginationInterceptor.setDialectType(dbType);

		final List<ISqlParser> sqlParserList = new ArrayList<>();
		// 攻击 SQL 阻断解析器、加入解析链
		sqlParserList.add(new BlockAttackSqlParser());

		// TODO 【技巧】动态表名 SQL 解析器
		final MyDynamicTableNameParser dynamicTableNameParser = new MyDynamicTableNameParser();
		final Map<String, ITableNameHandler> tableNameHandlerMap = new HashMap<String, ITableNameHandler>(1);
		tableNameHandlerMap.put(GlobalConstants.DYNAMIC_TABLE_NAME_PREFIX, new MyTableNameHandler());
		dynamicTableNameParser.setTableNameHandlerMap(tableNameHandlerMap);
		sqlParserList.add(dynamicTableNameParser);

		paginationInterceptor.setSqlParserList(sqlParserList);
		return paginationInterceptor;
	}

}
